<template>
  <div class="createMarketPrice" @click.stop="aotuTab=false">
    <el-button type="primary" style="width: 60px;margin-bottom: 10px" size="mini" @click="subMarker()">{{ $t('btn.save') }}</el-button>
    <el-tabs>
      <el-tab-pane :label="$t('market.mainProduct')">
        <el-form ref="purchaseRef" :model="prodValue" label-width="100px" :rules="prodValueRules">
          <el-form-item :label="$t('market.orderDate')">
            <el-date-picker
              v-model.trim="prodValue.fdate"
              type="date"
              style="width: 152px"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.priceListName')" prop="fname" label-width="110px">
            <el-input v-model.trim="prodValue.fname" size="mini" />
          </el-form-item>
          <el-form-item :label="$t('market.cust')" prop="fcustId">
            <el-autocomplete
              v-model.trim="prodValue.fcust"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              size="mini"
              @focus="queryTBdCustomerList"
              @select="clientData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="clientVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.currency2')" prop="fcurrencyId">
            <el-autocomplete
              v-model.trim="prodValue.fcurrencyIdName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              size="mini"
              @focus="queryTBdCurrency"
              @select="currencyData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="currencyVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.note')" prop="fnote" style="width: 33%">
            <el-input v-model.trim="prodValue.fnote" size="mini" />
          </el-form-item>
          <el-form-item v-if="false" label="是否含税">
            <el-checkbox v-model="prodValue.fisIncludedTax" />
          </el-form-item>
        </el-form>
        <div style="margin-bottom: 5px;">
          <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <jc-table
          :table-data="prodValue.priceDetails"
          :table-header="tableHeader"
          :table-height="tableHeight"
          serial
          @rowClick="rowClick"
          @cellClick="cellClick"
        >
          <el-table-column :label="$t('market.fmaterial')" prop="fmaterialId" align="center" width="150px">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.fnumber"
                size="mini"
                @input="getAtuo(scope.$index, scope.row.fnumber)"
              >
                <i
                  slot="prefix"
                  class="iconfont icon-jin-rud-ao-bo"
                  @click="sonJumpMateriel(scope.row.fnumber)"
                />
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleGetMateriel(scope.row, scope.$index)"
                />
              </el-input>
              <div v-if="aotuTab && tableIndex === scope.$index" :class="tableIndex<7 ? 'tabPosit': 'tabPosit1'">
                <number-code :fnumber="fnumber1" @material="materielSelectRow" />
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('shop.fname2')" prop="fname" align="center" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('market.fmodel')" prop="fmodel" align="center" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('shop.fspecificaTion')" prop="fspecificaTion" align="center" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('market.fdescripTion')" prop="fdescripTion" align="center" min-width="200px" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('market.saleUnit')" prop="funit" align="center" />
          <el-table-column :label="$t('market.priceCoeff')" prop="fpriceBase" align="center" width="80">
            <template slot-scope="scope">
              <el-input-number v-model.number="scope.row.fpriceBase" size="mini" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.fprice')" prop="fprice" align="center" width="80">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.fprice"
                size="mini"
                :precision="4"
                @change="scope.row.fdownPrice=scope.row.fprice"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.lowestPrice')" prop="fdownPrice" align="center" width="80">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.fdownPrice"
                size="mini"
                :precision="4"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.effectiveDate')" prop="feffectivedate" align="center">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.feffectivedate"
                value-format="yyyy-MM-dd"
                style="width: 130px"
                size="mini"
                type="date"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.expiryDate')" prop="fexpriydate" align="center">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.fexpriydate"
                value-format="yyyy-MM-dd"
                style="width: 130px"
                size="mini"
                type="date"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('market.handle')" min-width="80px" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="delectSale(scope.$index)">{{ $t('shop.delete') }}</el-button>
            </template>
          </el-table-column>
        </jc-table>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')">
        <jc-marker
          other-height="calc(100vh - 290px)"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    币别列表弹窗-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--客户列表-->
    <client v-if="clientVisiblit" :msg="prodValue.fcreateOrgId" @client="clientData" />
    <!--    物料弹窗-->
    <el-dialog
      v-dialogDrag
      :title="$t('menu.materielList')"
      model
      :visible.sync="isMaterielDialog"
      :close-on-click-modal="false"
      width="60%"
      top="5vh"
      destroy-on-close
      @close="closeNum"
    >
      <div class="materiel-form">
        <search :options="selectData" :msg="tacitly" @seek="collect" @hand="handleMaterielSearch" />
        <el-button size="mini" type="primary" class="btn" @click="handleMaterielSearch">{{ $t('btn.search') }}</el-button>
      </div>
      <jc-table
        :table-data="materielDialogData"
        :table-header="materielDialogHeader"
        table-height="53vh"
        get-row-keys="fmaterialId"
        serial
        @clickRow="materielSelectRow"
      />
      <jc-pagination
        v-show="materielPagination.total > 0"
        :total="materielPagination.total"
        :page.sync="materielPagination.pageNum"
        :limit.sync="materielPagination.pageSize"
        @pagination="handleGetMateriel"
      />
    </el-dialog>
  </div>
</template>
<script>
import {
  insertSalPrice
} from '@/api/marketManage/marketPriceList'
import jumpMateriel from '@/components/JumpMateriel'
import {
  queryMaterialList
} from '@/api/marketManage/marketOrder'
import jcMarker from '@/components/marker'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'

export default {
  name: 'CreateMarketPrice',
  components: {
    jcMarker,
    client: () => import('@/views/market/marketManage/createMarkerOrder/components/client'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    search,
    numberCode: () => import('@/components/NumberCode')
  },
  mixins: [jumpMateriel, searData, autocomplete],
  data() {
    return {
      val: [], // 多选数据
      rate: 1.13, // 销售基准价(默认13%税率)
      fdownPriceRate: '13', // 销售基准价税率
      ftype: 0,
      fbillNo: 'fnumber', // 编码
      clientVisiblit: false, // 客户弹窗
      disabled: false, // 税率是否禁用
      isMaterielDialog: false, // 物料弹窗
      aotuTab: false,
      fnumber1: '',
      materialId: '', // 物料ID
      // 物料弹窗分页
      materielPagination: {
        total: 0, // 总条目
        pageNum: 1, // 当前页
        pageSize: 200 // 每页显示多少条数据
      },
      FNUMBER: '', // 弹窗编码
      FDESCRIPTION: '', // 弹窗描述
      FSPECIFICATION: '', // 弹窗规格型号
      materielDialogData: [],
      materielDialogHeader: [ // 物料表头
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', minWidth: '130px' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.descrip'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.createDate'), prop: 'fcreateDate' }
      ],
      // 点击行的序号
      tableIndex: 0,
      tableHeader: [],
      tableHeight: '68vh',
      prodValue: {
        fdate: new Date(),
        fdocumentStatus: 'A',
        fcreateOrgId: 1, // 销售组织
        fname: '', // 价目表名称
        fcurrencyId: '', // 币别ID
        fdescripTion: '', // 备注
        fisIncludedTax: false, // 含税
        fcurrencyIdName: '', // 币别名称
        limitName: 0, // 限定客户
        fcust: '', // 选择客户
        fcustId: 0, // 客户ID
        priceDetails: [{
          fentryId: 0,
          fmaterialId: '', // 物料编码ID
          fnumber: '', // 物料编码
          funit: '', // 单位
          funitId: '', // 单位id
          fpriceBase: 1, // 销售系数
          fprice: '', // 出厂价
          fdownPrice: '', // 最低限价
          fexpriydate: '2100-01-01', // 失效期
          feffectivedate: new Date() // 生效期
        }]
      },
      prodValueRules: { // 是否填写验证
        fname: [
          { required: true, message: '请输入价目表名称', trigger: 'blue' }
        ],
        // fcreateOrgId: [
        //   { required: true, message: '请选择销售组织', trigger: 'change' }
        // ],
        fcurrencyId: [
          { required: true, message: '请选择币别', trigger: 'change' }
        ]
      },
      // 结算币别
      currencyVisiblit: false,
      otherUrlObject: {}, // 其它审核人
      priceIndex: []
    }
  },
  created() {
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 280px)' : '67vh'
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber1 = fnumber
      }, 1000)
    },
    // 保存
    subMarker() {
      this.$refs.purchaseRef.validate(valid => {
        if (!valid) {
          return false
        }
        for (const item of this.prodValue.priceDetails) {
          if (item.materialId === '') {
            this.$message.error('表格不能为空或删除空行')
            return false
          }
        }
        const DATA = this.prodValue
        insertSalPrice(DATA).then(res => {
          if (res.code === 0) {
            const fid = res.data
            // 关闭当前页面
            this.$store.dispatch('tagsView/guanbi', this.$route)
            // 跳转到修改页面
            this.$router.push({ path: `/markedEdit/${fid}` })
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 物料弹窗选中
    async materielSelectRow(item) {
      const items = this.prodValue.priceDetails[this.tableIndex]
      items.fmaterialId = item.fmaterialId
      items.fnumber = item.fnumber
      items.fname = item.fname
      items.funitId = item.fsaleUnitId
      items.funit = item.fsaleUnit
      items.fmodel = item.fmodel
      items.fspecificaTion = item.fspecificaTion
      items.fdescripTion = item.fdescripTion
      this.isMaterielDialog = false
    },
    closeNum() {
      this.isMaterielDialog = false
      this.materielPagination.pageNum = 1
      this.materielPagination.pageSize = 10
      Object.keys(this.searCollData).forEach(key => {
        this.searCollData[key] = ''
      })
    },
    // 打开物料编码
    async handleGetMateriel(row, index) {
      if (index || index === 0) {
        this.index = index // 点击时的下标，用于多选
        this.tableIndex = index
      }
      const DATA = {
        pageNum: this.materielPagination.pageNum,
        pageSize: this.materielPagination.pageSize,
        search: this.searCollData
      }
      const { data: RES } = await queryMaterialList(DATA)
      this.materielDialogData = RES.array
      this.materielPagination.total = RES.total
      this.isMaterielDialog = true
    },
    // 物料搜索
    handleMaterielSearch() {
      this.materielPagination.pageNum = 1
      this.handleGetMateriel()
    },
    // 获取客户数据(子传父)
    clientData(item) {
      if (item.fcustId) {
        this.prodValue.fcustId = item.fcustId
        this.prodValue.fcust = item.fname
        this.clientVisiblit = false
      } else {
        this.clientVisiblit = false
      }
    },
    // 选择币别
    currencyData(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.prodValue.fcurrencyIdName = item.fsettleCurrIdName || item.fname
        this.prodValue.fcurrencyId = item.fsettleCurrId || item.fcurrencyId
        this.currencyVisiblit = false
      } else {
        // 点击关闭按钮
        this.currencyVisiblit = false
      }
    },
    // 删除明细空行
    delectSale(index) {
      this.prodValue.priceDetails.splice(index, 1)
    },
    // 新增行
    newHang() {
      this.prodValue.priceDetails.push(
        {
          fmaterialId: '', // 物料编码ID
          fentryId: 0,
          fnumber: '', // 物料编码
          funit: '', // 单位
          funitId: '', // 单位id
          fpriceBase: 1, // 销售系数
          fprice: '', // 出厂价
          fdownPrice: '', // 最低限价
          fexpriydate: '2100-01-01', // 失效期
          feffectivedate: new Date() // 生效期
        }
      )
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.prodValue.priceDetails.splice(this.indexSelf, 1)
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.prodValue.priceDetails[this.subscript][this.property]
      this.prodValue.priceDetails.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.createMarketPrice {
  @include listBom;
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.5vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 99999!important;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left:0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .el-table {
    margin-top: 5px;

    &::v-deep td {
      padding: 8px 0;
    }

    &::v-deep thead.is-group th {
      padding: 3px 0;

      .el-input__inner {
        background: #e6ebfc;
        color: #909399;
        font-size: 12px;
        font-weight: 550;
        border: none;
      }
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 275px;
      margin-bottom: 0;
    }
  }
}

.el-input__icon {
  cursor: pointer;
}

.materiel-form {
  position: relative;
  width: 100%;
  bottom: 5px;
  .btn {
    transform: translateY(18%);
    margin-left: 450px !important;
    z-index: 999;
  }
  .btn1 {
    margin-left: 15px !important;
  }
}
</style>
